import 'dart:math';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/entity/home/AlbumEntity.dart';
import 'package:qianyi/entity/home/album_detail_list_entity.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:quds_ui_kit/screens/quds_bottom_sheet_container.dart';

import '../../../../controller/homeTabController.dart';
import '../../../../controller/imageDetailVideoController.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_entity.dart';
import '../../../../state/token.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../utils/DialogUtils.dart';
import '../../../../utils/throttle.dart';
import '../../../../view_model/home/AlbumDetailListModel.dart';
import '../../../../view_model/mine/album_view_model.dart';
import '../../../../wcao/ui/theme.dart';


class AlbumScreen extends StatefulWidget {
  @override
  _AlbumScreenState createState() => _AlbumScreenState();
}

class _AlbumScreenState extends State<AlbumScreen> {
  HomeTabController homeTabController = Get.find();
  TokenController tokenController = Get.find();
  AlbumEntity? albumEntity;
  List<String> images = [
    'https://example.com/image1.jpg', // 替换为实际图片链接
    'https://example.com/image2.jpg', // 替换为实际图片链接
    // 添加更多图片链接...
  ];
@override
  void initState() {
    getAlbumEntity();
    // TODO: implement initState
    super.initState();
  }
  getAlbumEntity() async {
    HudUtil.showBeautiful(context);
    Map<String,String> params1 = {
      "id":homeTabController.albumDetailId
    };
    HttpEntity httpEntity1 = await HttpManager.getInstance().request(url: '/platform/album/getAlbum',params: params1,method: Method.get) as HttpEntity;
    setState(() {
      albumEntity = AlbumEntity.fromJson(httpEntity1.getOriData()['data']);

    });
    HudUtil.dismiss();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("专辑详情"),
        actions: [
          IconButton(onPressed: (){
            showQudsModalBottomSheet(

                context,
                    (c) => Column(
                  children: [
                    // ListTile(
                    //   leading: Icon(Icons.edit),
                    //   title: Text('转入专辑'),
                    //   onTap: (){
                    //
                    //     // Get.toNamed("/edit/editPage");
                    //   },
                    // ),
                    ListTile(
                      leading: Icon(Icons.delete),
                      title: Text('删除专辑'),
                      onTap: (){
                        DialogUtils.showConfirmDialog(
                            context, "是否确认删除", "落子无悔删除后不可恢复").then((
                            result) async {

                          // if (result!) {
                          //   HudUtil.showBeautiful(context);
                          //   List<String> params = [];
                          //   params.add(imageVideoDetail.id!);
                          //
                          //   HttpEntity h = await HttpManager.getInstance().request(url: "/platform/imgDetail/deleteImgs/${tokenController.uid}",method: Method.post,listParams: params) as HttpEntity;
                          //   Get.toNamed("/home");
                          //
                          //   HudUtil.dismiss();
                          //   // uploadVideo();
                          //
                          // }
                        }

                        );
                      },
                    ),

                    albumEntity!.uid == tokenController.uid?
                    Container():ListTile(
                      leading: Icon(Icons.policy),
                      title: Text('收藏专辑'),
                      onTap: () async {
                        Navigator.pop(context);
                        HudUtil.showBeautiful(context);
                        Map<String, dynamic> params = {
                          "agreeCollectId": albumEntity!.id,
                          "agreeCollectUid": albumEntity!.uid!,
                          "type": 3,
                          "uid": tokenController.uid
                        };

                        await HttpManager.getInstance().request(url: '/platform/agreeCollect/collection',params: params,method: Method.post);
                        HudUtil.dismiss();
                     },
                    ),
                    ListTile(
                      leading: Icon(Icons.save),
                      title: Text('取消收藏'),
                      onTap: () async {
                        Navigator.pop(context);
                        HudUtil.showBeautiful(context);
                        Map<String, dynamic> params = {
                          "agreeCollectId": albumEntity!.id,
                          "agreeCollectUid": albumEntity!.uid!,
                          "type": 3,
                          "uid": tokenController.uid
                        };

                        await HttpManager.getInstance().request(url: '/platform/agreeCollect/cancelCollection',params: params,method: Method.post);
                        HudUtil.dismiss();
                      },
                    ),
                    ListTile(
                      leading: Icon(Icons.qr_code),
                      title: Text('修改专辑'),
                      onTap: (){
                        Get.toNamed("/mine/editAlbumScreen");
                      },
                    ),
                    ListTile(
                      leading: Icon(Icons.wechat),
                      title: Text('微信'),
                      onTap: (){},
                    ),
                    ListTile(
                      leading: Icon(Icons.camera_alt),
                      title: Text('朋友圈'),
                      onTap: (){},
                    ),
                    ListTile(
                      leading: Icon(Icons.language),
                      title: Text('新浪微博'),
                      onTap: (){},
                    ),
                    ListTile(
                      leading: Icon(Icons.link),
                      title: Text('复制链接'),
                      onTap: (){},
                    ),
                    ListTile(
                      leading: Icon(Icons.cancel),
                      title: Text('取消'),
                      onTap: (){},
                    ),
                  ],
                ),
                titleText: '操作');

          }, icon: Icon(Icons.share_location))
        ],
      ),
      body: albumEntity!=null?SafeArea(

          child: NestedScrollView(
            physics: NeverScrollableScrollPhysics(),

            headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[
                // 可替换成 SliverPinnedHeader
                SliverAppBar(
                  pinned:false,
                  primary: false,
                  toolbarHeight: 25,
                  expandedHeight: 126,
                  // backgroundColor: Colors.transparent,
                  leading: Text(''),
                  flexibleSpace: FlexibleSpaceBar(

                    background:  Column(
                      children: [
                        Text("${albumEntity!.name}",style: TextStyle(fontSize: 18),),
                        SizedBox(height: 5,),
                        Text('${albumEntity!.imgCount}条内容'),
                        SizedBox(height: 5,),

                        ClipOval(
                          child: FancyShimmerImage(imageUrl: '${albumEntity!.avatar!}',width: 30,height: 30,)
                        ),
                        SizedBox(height: 5,),

                        Text("${albumEntity!.username}")

                      ],
                    ),
                  )
                  ,
                ),
              ];
            },
            body: ChangeNotifierProvider(
                create: (BuildContext context) => AlbumDetailListModel(),
                child: Consumer<AlbumDetailListModel>(
                    builder: (context, viewModel, child) {
                      ;
                      return CustomRefresh(
                          physics: NeverScrollableScrollPhysics(),
                          isMaterialHeader:true,
                          controller: viewModel.refreshController,
                          enablePullUp: true,
                          enablePullDown: true,
                          onRefresh: () async {
                            viewModel.onRefresh();
                          },
                          onLoading: () async {
                            viewModel.onLoading();
                          },
                          child: SingleChildScrollView(
                            child: buildWateFall(viewModel),
                          )


                      );
                    })
            ),
          )):Text(""),
    );
  }

  double getRandomHeight() {
    // 生成一个随机高度
    double height = Random().nextDouble() * (200 - 80) + 168;
    return   height ;
  }
  buildWateFall(AlbumDetailListModel viewModel) {
    TokenController tokenController = Get.find();

    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
    return MasonryGridView.count(
      padding: EdgeInsets.all(0),
      // 展示几列
      crossAxisCount: 2,
      // 元素总个数
      itemCount: viewModel.datas.length,
      // 单个子元素
      itemBuilder: (BuildContext context, int index) {
        AlbumDetailEntity trendEntity = viewModel.datas[index];
        // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
        return GestureDetector(
          onTap: () async {

            HudUtil.showBeautiful(context);
            String uid = await tokenController.getUid();
            Map<String,dynamic> params = {
              "mid":trendEntity!.id,
              "uid": uid
            };
            HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
            imageDetailVideoController.imageDetailId.value = trendEntity!.id!;
            await imageDetailVideoController.getImageVideoDetail();

            HudUtil.dismiss();
            Get.toNamed("/ui/home/imageVideoDetail");

          },
          child: Card(
            margin: EdgeInsets.all(1.5),

            child: ClipRRect(
              borderRadius: BorderRadius.circular(4.0),
              child:  Column(
                children: [
                  FancyShimmerImage(
                    height: getRandomHeight(),
                    imageUrl: trendEntity.cover!,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [

                      Flexible(

                        child: Text(
                          trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                          overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                        ),

                      ),
                      Row(
                        children: [
                          Icon(
                            CupertinoIcons.heart,size: 14,
                            color: Colors.grey,),
                          Text(trendEntity.agreeCount as String)
                        ],
                      )



                    ],
                  )

                  ,


                ],
              ),
            ),
          ),
        );
      },

      // 纵向元素间距
      mainAxisSpacing: 0,
      // 横向元素间距
      crossAxisSpacing: 0,
      //本身不滚动，让外面的singlescrollview来滚动
      physics:const NeverScrollableScrollPhysics(),
      shrinkWrap: true, //收缩，让元素宽度自适应
    )

        ;


  }
}
